<?php
// +----------------------------------------------------------------------
// | 钉钉/企业微信 群机器人
// +----------------------------------------------------------------------

namespace helper\ali;

class Robot
{
    /**
     * 消息通知
     * @param array  $data 数据
     * @param string $type 类型 text,link,markdown,actionCard,feedCard
     * @return string
     */
    public static function message(array $data, string $type = 'text')
    {
        if (!in_array($type, ['text', 'link', 'markdown', 'actionCard', 'feedCard'])) {
            return false;
        }
        //提交的地址
        $webhook = "https://oapi.dingtalk.com/robot/send?access_token=d5a260515579ecc4014dc14559b18130ed31ab8171baf5999464198a7fbcf478";
        //推送的内容
        // text : ['content' => '[error] ' . $data['content']]
        // link/markdown : [title, text, picUrl, messageUrl]
        // actionCard : [title, text, btnOrientation, singleTitle, singleURL]
        // actionCard : [title, text, btnOrientation, btns => [[title,actionURL]]
        // feedCard : [links=> [title, text, picUrl, messageUrl]]
        $post = [
            'msgtype' => $type,
            $type     => $data
        ];
        $post_string = json_encode($post);
        return self::request_by_curl($webhook, $post_string);
    }

    private static function request_by_curl($remote_server, $post_string)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $remote_server);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Content-Type: application/json;charset=utf-8'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 线下环境不用开启curl证书验证, 未调通情况可尝试添加该代码
        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
}